package edu.vt.ece.rt.dstm.contention;

import edu.vt.ece.rt.dstm.Context;
import edu.vt.ece.rt.util.Logger.Logger;

/*
 * Hard working Transaction, who has opened more transaction wins
 */
public class Karma extends AbstractContentionPolicy{

	@Override
	public void init(Context context) {
		context.contentionMetadata = 0;
	}
	
	@Override
	public void open(Context context) {
		context.contentionMetadata = 1 + ((Integer)context.contentionMetadata);
	}
	
	@Override
	public int resolve(Context context1, Context context2) {
		Integer opendObjects1 = (Integer)context1.contentionMetadata;
		Integer opendObjects2 = (Integer)context2.contentionMetadata;
		
		Logger.debug(context1+":"+opendObjects1 + " vs " + context2+":"+opendObjects2);
		if(opendObjects1 < opendObjects2 || opendObjects1.equals(opendObjects2) && context1.getContextId() > context2.getContextId())
			return +1;
		else{
			return -1;
		}
	}

}
